package com.wits.qso.web.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springside.modules.web.Servlets;

import com.wits.platform.common.constants.UserType;
import com.wits.platform.common.constants.ViewType;
import com.wits.platform.common.constants.WebConstants;
import com.wits.platform.common.utils.DateUtil;
import com.wits.platform.common.utils.FileUtil;
import com.wits.platform.common.utils.PageUtil;
import com.wits.platform.common.utils.StringUtil;
import com.wits.platform.web.controller.BaseController;
import com.wits.platform.web.mvc.PageParam;
import com.wits.qso.common.enumerate.BusinessType;
import com.wits.qso.entity.Attachment;
import com.wits.qso.entity.StuAid;
import com.wits.qso.entity.Student;
import com.wits.qso.service.AttachmentService;
import com.wits.qso.service.StuAidService;
import com.wits.qso.service.StudentService;

@Controller
@RequestMapping(value = "qso/stuaid")
public class StuAidController extends BaseController {
	
	private static final String ATTRIBUTE_STUAID_UPLOAD_FILES = "stuaidUploadFiles";
	
	@Autowired
	private StuAidService stuAidService;
	@Autowired
	private AttachmentService attachmentService;
	@Autowired
	private StudentService studentService;
	
	@RequestMapping(value="/toList")
	public String toList(){
		return "qso/stuaid/list";
	}
	
	/**
	 * 加载信息列表
	 * @param model
	 * @param page
	 * @param req
	 * @return
	 */
	@RequestMapping(value="/list")
	@ResponseBody
	public String list(Model model,@ModelAttribute("page") PageParam page, HttpServletRequest req){
		Map<String, Object> searchParams = Servlets.getParametersStartingWith(req, "search_");
		Page<StuAid> listPage = stuAidService.findPage(StuAid.class, searchParams, page);
		model.addAttribute("searchParams", Servlets.encodeParameterStringWithPrefix(searchParams, "search_"));
		return PageUtil.toAjaxPageResult(listPage.getTotalElements(), listPage.getContent());
	}
	
	/**
	 * 课件列表上按钮的触发事件处理
	 * @param model
	 * @param viewType
	 * @param id
	 * @return
	 */
	@RequestMapping(value="/view/{viewType}")
	public String toView(Model model,@PathVariable String viewType,@RequestParam String id){
		if(ViewType.Add.getView().equals(viewType)){
			Student stu=null;
			if((UserType.STUDENT.getValue()).equals(getCurrentUser().getUserType())){
				stu=studentService.findByUserId(getCurrentUserId());
			}else{
				stu = new Student();
			}

			StuAid aid=new StuAid();
			aid.setStuid(stu);
			model.addAttribute(WebConstants.COMMAND,aid );
			model.addAttribute("attachments",null);
		}else{
			StuAid aid=stuAidService.getOne(id);
			List<Attachment> attachments=attachmentService.findByBusinessIdAndType(aid.getId(), BusinessType.STUAID.getValue());
			model.addAttribute(WebConstants.COMMAND, aid);
			if(attachments==null || attachments.size()==0)
			model.addAttribute("attachments",null);
			else
			model.addAttribute("attachments",attachments);
		}
		
		model.addAttribute("viewType", viewType);
		return "qso/stuaid/form";
	}
	
	@RequestMapping(value="/save",method=RequestMethod.POST)
	@ResponseBody
	public Object save(Model model,@RequestParam String id,@RequestParam String stuid,
			@RequestParam String name,@RequestParam String remark,@RequestParam String intro,
			@RequestParam String share,@RequestParam String viewType, HttpSession session){
		
		StuAid command=new StuAid();
		
		if (UserType.STUDENT.getValue().equals( getCurrentUser().getUserType() )) {
			if(!"".equals(id) && ""!=id && null!=id){
				command.setId(id);
			}
			command.setName(name);
			command.setIntro(intro);
			command.setRemark(remark);
			command.setShare(share);
		}
		
		if(ViewType.Add.getView().equals(viewType)){
			command.setDateCre(new Date());
			command.setUserCre(getCurrentUserId());
		}else{
			command.setDateUpd(new Date());
			command.setUserUpd(getCurrentUserId());
		}
		try {
			command.setStuid(studentService.findByUserId(getCurrentUserId()));
			StuAid temp= stuAidService.save(command);
			List<Attachment> tempList=new ArrayList<Attachment>();
			List<String> aidUploadFiles = (List<String>) session.getAttribute( ATTRIBUTE_STUAID_UPLOAD_FILES );
			
			if (null != aidUploadFiles) {
				for (int i = 0; i < aidUploadFiles.size(); i++) {
					Attachment ata =attachmentService.getOne(aidUploadFiles.get(i)) ;
					ata.setUserCre(getCurrentUserId());
					ata.setBusinessId(temp.getId());
					ata.setBusinessType(BusinessType.STUAID.getValue());
					attachmentService.save(ata);
				}
				session.removeAttribute( ATTRIBUTE_STUAID_UPLOAD_FILES );
			}
			
			return ajaxDoneSuccess(this.getText("save.success"));
		} catch (Exception e) {
			return ajaxDoneError(this.getText("save.failed"), e);
		}
	}
	
	@RequestMapping(value = "/upload")
	public void aidUpload(@RequestParam(value = "attachment") MultipartFile multipartFile, HttpSession session) {
		if (null != multipartFile) {

			List<String> uploadFiles = (List<String>) session.getAttribute( ATTRIBUTE_STUAID_UPLOAD_FILES );
			if (null == uploadFiles) {
				uploadFiles = new ArrayList<String>();
			}

			String uuid = UUID.randomUUID().toString().replace( "-", "" );
			Attachment attachment = new Attachment();
			// attachment.setId( UUID.randomUUID().toString() );
			attachment.setBusinessType( BusinessType.STUAID.getValue() );
			attachment.setDateCre( DateUtil.getNow() );
			attachment.setFileSize( multipartFile.getSize() );
			attachment.setOriginalName( multipartFile.getOriginalFilename() );
			attachment.setExtName( FilenameUtils.getExtension( multipartFile.getOriginalFilename() ) );

			String storagePath = WebConstants.UPLOAD_DIR + File.separator + BusinessType.STUAID.getValue();

			attachment.setFilePath( storagePath + File.separator + uuid + "." + attachment.getExtName() );
			attachment = attachmentService.save( attachment );
			try {
				FileUtil.upload( multipartFile, session.getServletContext().getRealPath( "/" ) + storagePath, uuid + "." + attachment.getExtName() );

				uploadFiles.add( attachment.getId() );
				session.setAttribute( ATTRIBUTE_STUAID_UPLOAD_FILES, uploadFiles );
			} catch (Throwable cause) {
				logger.error( cause.getMessage(), cause );
			}
		}
	}
	
	/**
	 * 删除文件
	 * @param request
	 * @param modelMap
	 * @param id
	 * @return
	 */
	@RequestMapping(value="/deleteFile")
	@ResponseBody
	public Object deleteFile(HttpServletRequest request,ModelMap modelMap,@RequestParam String id){
		String realPath = request.getRealPath("/");
		Attachment atta=attachmentService.getOne(id);
		if(attachmentService.deleteById(id)>0){
			File file=new File(realPath+"/"+atta.getFilePath());
			file.delete();
			atta.setFilePath("");
			attachmentService.save(atta);
		}
		return "true";
        
	}
	
	/**
	 * 
	 *方法摘要：文件下载
	 *@param
	 *@return String
	 */
	@RequestMapping(value="/downloadFile")
	public void downloadFile(HttpServletRequest request,HttpServletResponse response,@RequestParam String id){
		response.setCharacterEncoding("utf-8");
		response.setContentType("multipart/form-data");
		String realPath = request.getRealPath("/");
		Attachment attachment=attachmentService.getOne(id);
		response.setHeader("Content-Disposition", "attachment;fileName="+attachment.getOriginalName());
		try {
			String fileName = realPath + "\\" + attachment.getFilePath();
			File file=new File(fileName);
			System.out.println(file.getAbsolutePath());
			InputStream inputStream=new FileInputStream(file);
			OutputStream os=response.getOutputStream();
			byte[] b=new byte[1024];
			int length;
			while((length=inputStream.read(b))>0){
				os.write(b,0,length);
			}
			inputStream.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	
	/**
	 * 删除课件信息
	 * @param ids
	 * @return
	 */
	@RequestMapping(value = "/delete")
	@ResponseBody
	public Object delete(String ids){
		try {
			stuAidService.deleteInBatch(Arrays.asList(StringUtil.split(ids, ",")));
			return ajaxDoneSuccess(this.getText("delete.success"));
		} catch (Exception e) {
			return ajaxDoneError(this.getText("delete.failed"));
		}
	}
	
	/**
	 * 唯一键检查
	 * @param id
	 * @param oldId
	 * @return
	 */
	@RequestMapping(value="/checkUniqueId")
	@ResponseBody
	public boolean checkUniqueId(@RequestParam("id") String id,@RequestParam("oldId") String oldId){
		if(id.equals(oldId)){
			return true;
		}
		StuAid obj=stuAidService.getOne(id);
		return obj == null;
	}
}
